package com.bigdata.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSON;
import com.bigdata.utils.ResponseUtil;
import com.bigdata.model.AjaxResult;

/**
 * 全局异常处理
 *
 * @author lly
 */
@ControllerAdvice
public class GlobalControllerExceptionHandler {

    Logger logger = LoggerFactory.getLogger("GlobalControllerExceptionHandler");

    @ExceptionHandler(value = Exception.class)
    public void defaultErrorHandler(HttpServletRequest req, Exception e, HttpServletResponse response)
            throws Exception {
        String xReq = req.getHeader("x-requested-with");
        logger.error(e.getMessage(), e);
        if (StringUtils.isNotBlank(xReq) && "XMLHttpRequest".equalsIgnoreCase(xReq)) {
            // 是ajax异步请求
            AjaxResult<String> result = new AjaxResult<String>();
            result.setCode(AjaxResult.CODE_ERROR);
            result.setMessage("服务器端发生错误");
            String json = JSON.toJSON(result).toString();
            ResponseUtil.renderJson(response, json);
        } else {
            ResponseUtil.renderText(response, e.getMessage());
        }
    }
}
